package com.world.rickcloudendpoint.service.net.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: 服務初始化器
 * @author: jlsong
 * @date: 2021/12/08 22:16:09
 * @version: 1.0
 */
@Component
public class SocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    final SocketChannelHandler socketChannelHandler;

    public  SocketChannelInitializer(SocketChannelHandler socketChannelHandler) {
        this.socketChannelHandler = socketChannelHandler;
    }

    @Value("${netty.websocket.path}")
    private String websocketPath;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //15 秒客户端没有向服务器发送心跳则关闭连接
//        pipeline.addLast(new IdleStateHandler(15, 0, 0));
        // HTTP请求的解码和编码
        pipeline.addLast(new HttpServerCodec());
        // 主要用于处理大数据流，比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的; 增加之后就不用考虑这个问题了
        pipeline.addLast(new ChunkedWriteHandler());
        // 把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse，
        // 原因是HTTP解码器会在每个HTTP消息中生成多个消息对象HttpRequest/HttpResponse,HttpContent,LastHttpContent
        pipeline.addLast(new HttpObjectAggregator(8192));
        // 协议包长度限制
        pipeline.addLast(new WebSocketServerProtocolHandler(websocketPath, true, 5000));
        // 自定义消息处理器
        pipeline.addLast(socketChannelHandler);
    }
}
